package org.droid.campusorder;

import java.io.File;
import java.util.Hashtable;
import org.droid.R;
import org.droid.campusorder.action.RespGetAdAction;
import org.droid.campusorder.adapter.CanteenAdapter;
import org.droid.campusorder.bean.AdBean;
import org.droid.campusorder.bean.RespAdBean;
import org.droid.campusorder.common.CommonMethod;
import org.droid.campusorder.common.Config;
import org.droid.campusorder.common.Debug;
import org.droid.campusorder.common.GlobalData;
import org.droid.campusorder.manager.DownManager;
import org.droid.campusorder.manager.ApplicationManager;
import org.droid.campusorder.view.ViewAboutAD;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;

public class MainActivity extends MyActivity implements CommonMethod {
	private RespGetAdAction rgaAction;
	private RespAdBean rab;
	private Hashtable<String, String> ht;
	private int VIEW_AD_ID = 7; // ViewAboutAD的ID号
	private static ViewAboutAD mViewAboutAD;
	private LinearLayout mLinearLayout;
	private RelativeLayout mRelativeLayout;
	public static ImageView[] images;
	private View mainView;
	private ImageButton ib_search;
	// private View load_page;
	public ListView canteenList;
	private String[] AdLinkPaths; // 点击广告图片打开的链接地址
	private static String[] AdPicSrcPaths; // 用于存放广告图片地址
	private Debug debug;
	private AdPicsAsyncTask adPicsAsyncTask;// 异步下载广告图片

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		debug = new Debug("MainActivity");
		adPicsAsyncTask = new AdPicsAsyncTask();
		LayoutInflater inflater = getLayoutInflater();
		mainView = inflater.inflate(R.layout.main, null);
		setContentView(mainView);
		findAllViewById();
		CanteenAdapter cabteenAdapter = new CanteenAdapter(
				getApplicationContext());
		canteenList.setAdapter(cabteenAdapter);
		setListenner();
		// 发送广告请求
		reqNewAd();
	}

	@Override
	public void setListenner() {
		// 搜索按钮的监听
		ib_search.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), SearchActivity.class);
				startActivity(intent);
			}
		});
		// 食堂List点击事件的监听
		canteenList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent = new Intent();
				Bundle mBundle = new Bundle();
				mBundle.putInt("CanteenContentPosition", arg2);
				intent.putExtras(mBundle);
				intent.setClass(getApplicationContext(),
						CanteenShopActivity.class);
				startActivity(intent);
			}
		});
	}

	@Override
	public void findAllViewById() {
		ib_search = (ImageButton) mainView.findViewById(R.id.ib_search);
		canteenList = (ListView) findViewById(R.id.listView1);
		mRelativeLayout = (RelativeLayout) mainView
				.findViewById(R.id.relativelayout);
	}

	// ** 设置ViewAD的布局 *//*
	@SuppressWarnings("static-access")
	public void setViewADLayout() {
		mViewAboutAD = new ViewAboutAD(getApplicationContext());
		mViewAboutAD.setDrawableResources(AdPicSrcPaths);
		mViewAboutAD.setId(VIEW_AD_ID);
		for (int i = 0; i < AdPicSrcPaths.length; i++) {
			View childView = new View(this);
			File file = new File(AdPicSrcPaths[i]);
			if (file.exists()) {
				Bitmap bmp = BitmapFactory.decodeFile(AdPicSrcPaths[i]);
				ImageView imageView = new ImageView(this);
				imageView.setImageBitmap(bmp);
				childView = imageView;
				bmp = null;
			} else {
				LayoutInflater inflater = LayoutInflater.from(this);
				childView = inflater.inflate(R.layout.progress_loading, null);
			}
			// 配置imageview的布局参数，宽度和高度都FILL_PARENT
			LinearLayout.LayoutParams ll_lp = new LinearLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
			mViewAboutAD.setLayoutParams(ll_lp);
			RelativeLayout.LayoutParams rl_lp = new RelativeLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
			rl_lp.addRule(RelativeLayout.CENTER_IN_PARENT, VIEW_AD_ID);
			mViewAboutAD.setLayoutParams(rl_lp);
			mViewAboutAD.addView(childView);
		}

	}

	/** 设置小圆点条布局 */
	public void setPointImagView() {
		// 动态添加布局
		mLinearLayout = (LinearLayout) this.getLayoutInflater().inflate(
				R.layout.main_scroller_pointbar, null);
		// 设置子布局的宽和高
		LinearLayout.LayoutParams LP_FF = new LinearLayout.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		mLinearLayout.setLayoutParams(LP_FF);
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
				ViewGroup.LayoutParams.FILL_PARENT, // width
				ViewGroup.LayoutParams.WRAP_CONTENT // height
		);
		// 设置自布局的底边与ADview的底边对齐
		lp.addRule(RelativeLayout.ALIGN_BOTTOM, VIEW_AD_ID);
		mLinearLayout.setLayoutParams(lp);
		// 向子布局中填充小圆点
		int imageSize = AdPicSrcPaths.length;
		images = new ImageView[imageSize];
		images[0] = new ImageView(this);
		images[0].setImageResource(R.drawable.point_sel);
		images[0].setPadding(0, 0, 5, 0);
		mLinearLayout.addView(images[0]);
		for (int i = 1; i < images.length; i++) {
			images[i] = new ImageView(this);
			images[i].setPadding(0, 0, 5, 0);
			images[i].setImageResource(R.drawable.point);
			mLinearLayout.addView(images[i]);
		}
	}

	@Override
	public void onBackPressed() {
		setExitDialog();
	}

	/** 从SD卡指定路径获取广告图片来填充Adview */
	private void setAdSrc() {
		int length = GlobalData.adBeanList.size();
		AdPicSrcPaths = new String[length];
		AdLinkPaths = new String[length];
		for (int i = 0; i < length; i++) {
			String linkAdress = GlobalData.adBeanList.get(i).getDesc();
			String AdPicPath = GlobalData.dirPath
					+ "Ad/"
					+ DownManager.getImageFileName(GlobalData.adBeanList.get(i)
							.getPic());
			AdPicSrcPaths[i] = AdPicPath;
			AdLinkPaths[i] = linkAdress;
		}
	}


	private void reqNewAd() {
		rgaAction = new RespGetAdAction(MainActivity.this);
		// 添加请求参数
		ht = new Hashtable<String, String>();
		ht.put("forword", "GetAd");
		try {
			rab = (RespAdBean) rgaAction.getMsgFromNetwork(null,
					Config.SubConfig.Req, ht);
			ht = null;
			rgaAction = null; // 不用的对象设置为null
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (GlobalData.adBeanList != null) {
			GlobalData.adBeanList.clear();
		}
		GlobalData.adBeanList = rab.getAdBeanList();
		setAdSrc();
		setViewADLayout();
		setPointImagView();
		mRelativeLayout.addView(mViewAboutAD);
		mRelativeLayout.addView(mLinearLayout);
		adPicsAsyncTask.execute("startdownload");// 里面的值是随便传的
	}

	public static Handler autoPlayHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			mViewAboutAD.snapToScreen(msg.what);
		}
	};

	public Handler initADViewHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// setViewADLayout();
			// setPointImagView();
			// mRelativeLayout.addView(mViewAboutAD);
			// mRelativeLayout.addView(mLinearLayout);
			// load_page.setVisibility(View.GONE);
			ImageView imageView = new ImageView(getApplicationContext());
			Bitmap bmp = BitmapFactory.decodeFile(AdPicSrcPaths[msg.what]);
			imageView.setImageBitmap(bmp);
			bmp = null;
			mViewAboutAD.removeViewAt(msg.what);
			mViewAboutAD.addView(imageView, msg.what);
			View childView = mViewAboutAD.getChildAt(msg.what);
			final String tempLinkPath = AdLinkPaths[msg.what];
			childView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Uri uri = Uri.parse(tempLinkPath);
					Intent intent = new Intent(Intent.ACTION_VIEW, uri);
					startActivity(intent);
				}
			});
		}
	};

	public Handler exitHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				exitApp();
				break;

			default:
				break;
			}
		};
	};

	public void exitApp() {
		mViewAboutAD.closeTimer();
		ApplicationManager.getInstance().exit();
	}

	private void setExitDialog() {
		AlertDialog.Builder builder = new Builder(MainActivity.this);
		builder.setMessage("确认退出吗？");
		builder.setTitle("提示");
		builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				exitHandler.sendEmptyMessage(0);
			}
		});

		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.create().show();
	}

	private class AdPicsAsyncTask extends AsyncTask<String, Integer, Bitmap> {
		@Override
		protected Bitmap doInBackground(String... params) {
			File file;
			int length = GlobalData.adBeanList.size();
			for (int i = 0; i < length; i++) {
				AdBean ab = GlobalData.adBeanList.get(i);
				System.out.println("广告名字：" + ab.getName());
				System.out.println("广告pic：" + ab.getPic());
				// 设置下载的广告图片的文件名及路径
				String fileDir = GlobalData.dirPath + "Ad/";
				File fileFolder = new File(fileDir);
				if (!fileFolder.exists()) {
					fileFolder.mkdirs();
				}
				String imagePath = fileDir
						+ DownManager.getImageFileName(ab.getPic());
				file = new File(imagePath);
				if (!file.exists()) {// 若文件存在则不下载
					debug.debug("开始下载====================================");
					debug.debug("Strat-->>download file:" + imagePath);
					try {
						DownManager.downImage(ab.getPic(), imagePath);
						publishProgress(i);
					} catch (Exception e) {
						debug.debug(e.getMessage());
						e.printStackTrace();
					}
					debug.debug("download file:" + imagePath);
				} else {
					publishProgress(i);
				}
			}
			return null;
		}

		protected void onProgressUpdate(Integer... progress) {// 在调用publishProgress之后被调用，在ui线程执行
			initADViewHandler.sendEmptyMessage(progress[0]);
			// canteenShopAdapter.notifyDataSetChanged();
		}

		protected void onPostExecute(Bitmap result) {// 后台任务执行完之后被调用，在ui线程执行
			debug.debug("————————————————————————————————over~");

		}

		protected void onPreExecute() {// 在doInBackground(Params...)之前被调用，在ui线程执行
		}

		protected void onCancelled() {// 在ui线程执行
		}
	}
}